package com.example.houseweb.intercept;

import com.example.housecommon.constants.CommonConstant;
import com.example.housecommon.model.User;
import com.google.common.base.Joiner;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author ：Anitaxiaofeng
 * @description：
 * @create 2018-05-28
 **/
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //处理url中的errorMsg，要弹出错误信息，所以要存在request中
        Map<String,String[]> map = httpServletRequest.getParameterMap();
        map.forEach((k,v)->{
            if(k.equals("errorMsg")||k.equals("successMsg")||k.equals("target")){
                httpServletRequest.setAttribute(k, Joiner.on(",").join(v));
            }
        });
        String reqUri = httpServletRequest.getRequestURI();
        if(reqUri.startsWith("/static") || reqUri.startsWith("/error")) {
            return true;
        }
        HttpSession session = httpServletRequest.getSession(true);
        User user = (User)session.getAttribute(CommonConstant.USER_ATTRIBUTE);
        //user == null 留给AuthActionInterceptor处理 这个Intercepter就是将user放到ThreadLocal中
        if(user != null) {
            UserContext.setUser(user);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }


    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        UserContext.remove();
    }
}


